package com.spider.admin.service.agent;

import com.spider.admin.conf.ResultMessage;
import com.spider.admin.exception.SpiderException;
import com.spider.admin.http.entity.PageResult;
import com.spider.admin.store.primary.mapper.AgentOptionsMapper;
import com.spider.admin.store.primary.model.AccountInfo;
import com.spider.admin.store.primary.model.AgentOption;
import com.spider.admin.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AgentOptionServiceImpl implements AgentOptionService {

    @Autowired
    private AgentOptionsMapper agentOptionsMapper;

    @Override
    public PageResult<AgentOption> queryAgentOptionList(Integer page, Integer pageSize, String section) throws SpiderException {
        page = page == null || page.intValue() <= 0 ? 1 : page;
        pageSize = pageSize == null ? 10 : pageSize;
        long totalCount = agentOptionsMapper.queryAgentOptionsNum(section, null).longValue();
        int totalPage = (int) Math.ceil((double) totalCount / (double) pageSize);
        page = page > totalPage ? totalPage : page;
        page = page <= 0 ? 1 : page;
        PageResult<AgentOption> result = new PageResult<>();
        result.setCurrentPage(page);
        result.setPageSize(pageSize);
        result.setTotal(totalCount);
        result.setTotalPage(totalPage);

        List<AgentOption> records = agentOptionsMapper.queryAgentOptions((page - 1) * pageSize, pageSize, section, null);
        result.setList(records);
        return result;
    }

    @Override
    public int saveAgentOption(AgentOption agentOption) throws SpiderException {
        int rows = 0;
        List<AgentOption> oldList = agentOptionsMapper.queryAgentOptions(0, 10, agentOption.getSection(), agentOption.getOptionItem());
        if (StringUtils.isEmpty(agentOption.getPid())) {
            if (oldList != null && oldList.size() > 0) {
                throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "相同配置项不能重复添加");
            }
            agentOption.setPid(CommonUtil.getUniqueKey());
            rows = agentOptionsMapper.saveAgentOption(agentOption);
        } else {
            if (oldList != null && oldList.size() > 0 && !oldList.get(0).getPid().equals(agentOption.getPid())) {
                throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "相同配置项不能重复添加");
            }
            rows = agentOptionsMapper.updateAgentOption(agentOption.getPid(), agentOption);
        }
        return rows;
    }

    @Override
    @Transactional
    public int deleteAgentOption(String pid) throws SpiderException {
        return agentOptionsMapper.deleteAgentOption(pid);
    }
}
